package com.project.web.controller;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;

import com.project.entity.sys.BaseEntity;
import com.project.service.BaseService;

public abstract class BaseController<T extends BaseEntity> {
	
	@Autowired
	private BaseService<T> service;
	
	protected abstract Class<T> getClazz();
	
	private T entity;

	public T getEntity() {
		return entity;
	}

	public void setEntity(T entity) {
		this.entity = entity;
	}



	/**
	 * �?有RequestMapping调用钱的model绑定方法�?
	 * 先根据form的id从数据查询出对象，再把form
	 * 提交的内容绑定到该对象上。只有在接受到id参数
	 * 该方法才被调�?
	 */
	@ModelAttribute
	public void prepare(@RequestParam(required=false,value="id") Long id,Model model){
		if(id != null){
			entity = service.getById(id);
		}else{
			try {
				entity =   getClazz().newInstance();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		model.addAttribute("entity", entity);
		
	}
	
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
        binder.registerCustomEditor(Timestamp.class, new CustomDateEditor(datetimeFormat, true)); 
        binder.registerCustomEditor(Time.class, new CustomDateEditor(timeFormat, true)); 
	}
	
}


